import 'package:easydouban/bean/i_movie_favorite_entity.dart';
import 'package:easydouban/provider/movie_provider.dart';
import 'package:easydouban/sql/sql_manager.dart';
import 'package:easydouban/tools/starRating.dart';
import 'package:easydouban/tools/toastTool.dart';
import 'package:easydouban/ui/movie_detail.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:pk_skeleton/pk_skeleton.dart';
import 'package:provider/provider.dart';

import '../../bean/i_top_entity.dart';
import '../../sql/exe/favorite_sql.dart';
import '../../viewModel/future_model.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>{
  final ScrollController _scrollController = ScrollController();
  static const double _imageWidth = 120.0;
  static const double _imageHeight = 150.0;
  int limit = 3,skip = 0;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent){
        skip += limit;
        _loadMovieData();
      }
    });
  }

  ///上拉加载
  Future _loadMovieData() async{
      await getTopList(skip,limit).then((value){
          ///context.read<T>  需要对provider的更新(set)操作
         ///context.watch<T>  需要对provider的读取(get)操作
          final movieProvider = context.read<MovieProvider>();
          if(value != null){
            movieProvider.setList = value;
          }
        });
  }

  ///电影ListView
  ///电影Provider修改作用域
  Widget _buildMovie(List<ITopEntity> entityList){
    return Consumer<MovieProvider>(
      builder: (ctx,movieProvider,child){
        return ListView.builder(
            itemCount: movieProvider.getList.length,
            controller: _scrollController,
            itemBuilder:(context,index){
              return createMovieItem(movieProvider.getList[index],index);
            });
      },
    );
  }

  ///加载第一次初始化显示数据
  ///不要将此内容与'_buildMovie'放在一起，不然，数据发生变化会进行rebuild,
  ///暂且将原因定为：下列内容涉及到数据变化，会产出数据监听，因此会rebuild他的widget
  ///此处存在警告（已经解决）
  ///======== Exception caught by foundation library ====================================================
  // The following assertion was thrown while dispatching notifications for MovieProvider:
  // setState() or markNeedsBuild() called during build.
  //
  // This _InheritedProviderScope<MovieProvider> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
  // The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<MovieProvider>
  //   value: Instance of 'MovieProvider'
  //   listening to value
  // The widget which was currently being built when the offending call was made was: FutureBuilder<List<ITopEntity>?>
  //   dirty
  //   state: _FutureBuilderState<List<ITopEntity>?>#aba8e
  void _loadMovieList(List<ITopEntity> entityList){
    if(skip == 0){
      final movieProvider = context.read<MovieProvider>();
      movieProvider.setList = entityList;
    }
  }

  ///FutureBuild+骨架屏
  ///FutureBuild会执行两次，第一次状态为waiting，第二次为done（在正常情况下）
  Widget _buildFutureBuild(BuildContext context, AsyncSnapshot<List<ITopEntity>?> snapshot){
    switch(snapshot.connectionState){
      case ConnectionState.none:
        return const Text('未开始网络请求...');
      case ConnectionState.active:
        return const Text('开始网络请求...');
      case ConnectionState.waiting:
        return PKCardPageSkeleton(totalLines: 6);
      case ConnectionState.done:
        if(snapshot.hasError) {
          return const Text('请求过于频繁,请稍后再试...');
        }else{
         if(snapshot.data == null) {
           return const Center(child: Text('请求过于频繁,请稍后再试...'));
         } else {
           Widget widget = _buildMovie(snapshot.data!);
           WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
             _loadMovieList(snapshot.data!);
           });
           return widget;
         }
        }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(10.0),
      color: Colors.white,
      child: FutureBuilder(
          future: getTopList(skip, limit),
          builder: _buildFutureBuild
      ),
    );
  }

  ///占位图
  Widget placeholder = Container(
    width: double.infinity,
    height: _imageHeight,
    decoration: const BoxDecoration(
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        image: DecorationImage(image: AssetImage('assets/images/placeholder.png'),fit: BoxFit.fill),
        //color: Colors.grey
    ),
  );

  ///每一个电影介绍item
  Widget createMovieItem(ITopEntity entity,int index){
    return GestureDetector(
      onTap: (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => MovieDetailPage(entity.doubanId,entity.data[0].name)));
      },
      child: SizedBox(
          //width: _imageWidth,
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(flex: 2,child: createRank(entity.data[0].poster,index)),
                  Expanded(flex: 6,child: createMovieBanner(entity))
                ],
              ),
              createMovieName(entity),
              createMovieRating(entity),
              createMovieDescribe(entity),
              createMovieAlias(entity.alias)
            ],
          )
      ),
    );
  }

  ///排名勋章
  Widget createRankMedal(int rank){
    return ClipRRect(
      borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(20.0),bottomRight: Radius.circular(20.0)),
      child: Container(
        padding: const EdgeInsets.all(5.0),
        color: getRankColor(rank),
        child: Center(
          child: Text('${rank+1}', style: const TextStyle(fontSize: 16.0,fontWeight: FontWeight.bold,color: Colors.white),
          ),
        ),
      ),
    );
  }

  ///创建电影item左列图片+排名
  Widget createRank(String imgUrl,int rank){
    return Stack(
      alignment: Alignment.topLeft,
      children: [
        _createMovieImage(imgUrl),
        Positioned(
            top: 0,
            left: 0,
            child: createRankMedal(rank))
      ],
    );
  }
  ///公用圆角图片
  Widget _createMovieImage(String imgUrl){
    return ClipRRect(
      borderRadius: const BorderRadius.all(Radius.circular(10.0)),
      child: Image.network(
        imgUrl,
        height: _imageHeight,
        fit: BoxFit.cover,
      frameBuilder:(context,child, frame,wasSynchronouslyLoaded){
        if(wasSynchronouslyLoaded){
          return child;
        }else{
          return AnimatedSwitcher(
            duration: const Duration(milliseconds: 500),
            child: frame != null ? child : placeholder,
          );
        }
      },
      errorBuilder: (context,error, stackTrace,){
        return placeholder;
      },
    ),
    );
  }

  ///电影item右侧轮播图
  Widget createMovieBanner(ITopEntity entity){
    String shareImage = '';
    if(entity.data[0].shareImage.isEmpty){
      getShareImage(entity.doubanId).then((value) => {
        if(value != null){
          shareImage = value.image
        }
      });
    }else{
      shareImage = entity.data[0].shareImage;
    }
    var images = [shareImage,entity.data[0].poster];
    return Swiper(
      itemCount: images.length,
      itemHeight: _imageHeight,
      itemWidth: double.infinity,
      layout: SwiperLayout.TINDER,
      itemBuilder: (context,index){
        return _createMovieImage(images[index]);
      },
      pagination: const SwiperPagination(),
    );
  }

  ///创建电影名称和想看Icon,Row
  Widget createMovieName(ITopEntity entity) {
    return Container(
      margin: const EdgeInsets.only(top: 10.0),
      child: Row(
        children: [
          const Icon(
            Icons.slow_motion_video,
            color: Colors.red,
          ),
          Text(
            entity.data[0].name,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: const EdgeInsets.only(right: 20.0),
              child: const Align(
                  alignment: Alignment.topRight,
                  child: Icon(Icons.add_reaction_outlined,
                      color: Colors.orange)),
            ),
          )
        ],
      ),
    );
  }

  ///创建电影评分row
  Widget createMovieRating(ITopEntity entity) {
    return Container(
      margin: const EdgeInsets.only(top: 2.0),
      child: Row(
        children: [
          StarRating(double.parse(entity.imdbRating.isNotEmpty? entity.imdbRating : '0'), 5),
          Container(
            margin: const EdgeInsets.only(left: 5.0),
            child: Text(entity.imdbRating,
                style: const TextStyle(
                    fontSize: 12,
                    color: Colors.orange,
                    fontWeight: FontWeight.bold)),
          ),
          Expanded(
            flex: 1,
            child: Container(
                margin: const EdgeInsets.only(right: 20.0),
                child: GestureDetector(
                  child: const Text(
                    '收藏',
                    textAlign: TextAlign.right,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 12,
                        color: Colors.orange,
                        fontWeight: FontWeight.bold),
                  ),
                  onTap: () {
                    ///点击收藏按钮，将此item添加到数据库
                    exeFavoriteInsert(MovieFavorite(
                        entity.doubanId,
                        entity.data[0].poster,
                        entity.data[0].name,
                        entity.data[0].country,
                        entity.data[0].language,
                        entity.data[0].genre,
                        entity.data[0].description),context);
                  },
                )),
          )
        ],
      ),
    );
  }

  ///创建电影年/国家/类型
  Widget createMovieDescribe(ITopEntity entity){
    return Align(
      alignment: Alignment.topLeft,
      child: Text(
        '${entity.year}/${entity.data[0].country}/${entity.data[0].genre}',
        textAlign: TextAlign.start,
        style: const TextStyle(
          fontSize: 10.0,
          color: Colors.grey
        ),
      ),
    );
  }

  ///电影描述
  Widget createMovieAlias(String alias){
    if(alias.isEmpty){
      alias = 'unknown';
    }
    return Container(
      margin: const EdgeInsets.only(top: 10.0,bottom: 30.0,right: 10.0),
      child: Align(
        alignment: Alignment.topLeft,
        child: Text(
          alias,
          textAlign: TextAlign.start,
          maxLines: 2,
          style: const TextStyle(
              fontSize: 12.0,
              color: Colors.black,
              overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    );
  }

  ///排名颜色
  Color getRankColor(int rank){
    if(rank == 0){
      return Colors.amber;
    }else if(rank == 1){
      return Colors.lightBlue;
    }else if(rank == 2){
      return Colors.brown;
    }
    return Colors.grey;
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }
}

